package cn.iocoder.yudao.module.shop.service.opthistory;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.shop.controller.admin.opthistory.vo.ShopOptHistoryCreateReqVO;
import cn.iocoder.yudao.module.shop.controller.admin.opthistory.vo.ShopOptHistoryPageReqVO;
import cn.iocoder.yudao.module.shop.controller.admin.opthistory.vo.ShopOptHistoryRespVO;
import cn.iocoder.yudao.module.shop.convert.opthistory.ShopOptHistoryConvert;
import cn.iocoder.yudao.module.shop.dal.dataobject.opthistory.ShopOptHistoryDO;
import cn.iocoder.yudao.module.shop.dal.dataobject.order.ShopOrderDO;
import cn.iocoder.yudao.module.shop.dal.mysql.opthistory.ShopOptHistoryMapper;
import cn.iocoder.yudao.module.shop.dal.mysql.order.ShopOrderMapper;
import cn.iocoder.yudao.module.shop.service.order.ShopOrderService;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;

import javax.annotation.Resource;

import static cn.iocoder.yudao.module.shop.enums.ErrorCodeConstants.ORDER_NOT_EXISTS;

/**
 * 店内项目记录 Service 实现类
 *
 * @author 曹建伟
 */
@Service
@Validated
public class ShopOptHistoryServiceImpl implements ShopOptHistoryService{

    @Resource
    private ShopOptHistoryMapper shopOptHistoryMapper;

    @Resource
    private ShopOrderService shopOrderService;

    @Resource
    private ShopOrderMapper shopOrderMapper;

    @Override
    public Long create(ShopOptHistoryCreateReqVO createReqVO){

        ShopOrderDO shopOrderDO = shopOrderMapper.selectById(createReqVO.getOrderId());
        if(shopOrderDO == null){
            throw exception(ORDER_NOT_EXISTS);
        }

        ShopOptHistoryDO shopOptHistoryDO = ShopOptHistoryConvert.INSTANCE.convert(createReqVO);
        shopOptHistoryDO.setUserId(shopOrderDO.getUserId());
        shopOptHistoryDO.setMemberId(shopOrderDO.getMemberId());
        shopOptHistoryMapper.insert(shopOptHistoryDO);

        shopOrderDO.setHistoryId(shopOptHistoryDO.getId());
        shopOrderMapper.updateById(shopOrderDO);

        return shopOptHistoryDO.getId();
    }

    @Override
    public ShopOptHistoryDO get(Long id){
        return shopOptHistoryMapper.selectById(id);
    }

    @Override
    public PageResult<ShopOptHistoryDO> getHistoryPage(ShopOptHistoryPageReqVO reqVO){
        return shopOptHistoryMapper.selectPage(reqVO);
    }
}
